package com.jdrx.sw.sewage.utils;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Objects;

/**
 * @author samdy
 * @title: JsonSerializerUtils
 * @projectName sw-sewage-starter
 * @description: duoble类型保留两位小数
 * @date 2021/7/1515:01
 */
public class JsonSerializerUtils extends JsonSerializer<Double> {
    @Override
    public void serialize(Double value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (Objects.nonNull(value)) {
            //保留2位小数#代表末位是0舍去
            DecimalFormat decimalFormat = new DecimalFormat("0.##");
            //四舍五入
            decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
            String result = decimalFormat.format(value);
            jsonGenerator.writeNumber(Double.valueOf(result));
        } else {
            jsonGenerator.writeNumber(Double.valueOf(0));
        }
    }
}
